from django.template import Library
from django.conf import settings
import re
from collections import OrderedDict


register = Library()


@register.inclusion_tag("rbac/menu.html")
def menu(request):
    menu_dict = request.session.get(settings.MENU_SESSION_KEY)

    # 有序字典
    ordered_dict = OrderedDict()

    for key in sorted(menu_dict):
        ordered_dict[key] = menu_dict[key]
        # 一级菜单默认关闭
        ordered_dict[key]['class'] = "hide"

        for node in menu_dict[key]["children"]:
            reg = "^%s$" % node["url"]
            if request.current_menu_id == node["id"]:
                # 二级菜单选择效果展示
                node["class"] = "active"
                # 展开一级菜单
                ordered_dict[key]['class'] = ""

    return {"menu_dict": ordered_dict}


@register.inclusion_tag("rbac/breadcrumb.html")
def breadcrumb(request):
    breadcrumb_list = request.breadcrumb_list
    return {"breadcrumb_list": breadcrumb_list}


@register.filter
def has_permission(request, name):
    permission_dict = request.session.get(settings.PERMISSION_SESSION_KEY)

    if name in permission_dict:
        return True